const {
  decodeGPS
} = require('../../../utils/decodeGPS.js')
const {
  CityModel
} = require('../../../utils/city-model.js')
const cityModel = new CityModel()
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
const {
  globalData
} = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: globalData.isIphoneX,
    shops: [],
    city: '定位中',
    cityCode: '',
    detailAddr: '定位中...',
    GPScity: '',
    GPScityCode: '',
    isShopsInfo: false, //无数据显示的提示
    selectCity: null,
    promptContent: "",
    assetId: "", //资产id
    showModal: false, //弹出层
    selectShopId: "", //选择的门店id
    disabled: false,
  },

  goChooseCity() {
    wx.navigateTo({
      url: `/pages/chooseCity/index?city=${this.data.GPScity}&cityCode=${this.data.GPScityCode}`
    })
  },

  refreshAddr() {
    this.setData({
      detailAddr: '定位中...',
    }, function () {
      const selectCity = this.data.selectCity
      decodeGPS().then(res => {
        const {
          addressComponent,
          formatted_address,
          cityCode
        } = res
        this.setData({
          detailAddr: formatted_address,
          GPScity: addressComponent.city.replace('市', ''),
          GPScityCode: cityCode
        })
        if (!selectCity) {
          this.setData({
            city: addressComponent.city.replace('市', ''),
            cityCode,
            selectCity: {
              name: addressComponent.city.replace('市', ''),
              code: cityCode
            }
          })
        }
        this.cityList()
      }).catch(err => {
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userLocation']) {
              wx.showToast({
                title: '定位失败',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showModal({
                title: '提示',
                content: '没有授权定位信息，打开设置',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          }
        })
      })
    })
  },

  getLocation() {
    const selectCity = this.data.selectCity
    if (selectCity) {
      this.setData({
        city: selectCity.name,
        cityCode: selectCity.code
      })
    }
    this.refreshAddr()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      assetId: options.assetId
    })
  },

  /**
   * 获取门店信息
   */
  cityList: function () {
    var param = {}
    param.cityName = this.data.city;
    param.merchantId = wx.getStorageSync('merchantId');
    cityModel.getCityName(param).then(data => {
      if (data && data.length > 0) {
        this.setData({
          shops: data,
          isShopsInfo: false,
          promptContent: "这是距离您最近的店铺：",
        })
      } else {
        this.setData({
          shops: [],
          isShopsInfo: true,
          promptContent: "",
        })
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
      })
    })
  },

  /**
   * 绑定优惠券
   */
  bindCoupon: function () {
    if (this.data.assetId) {
      this.setData({
        disabled: true,
      })
      memberModel.userCouponUse({
        merchantId: wx.getStorageSync('merchantId'),
        shopId: this.data.selectShopId, //门店Id
        type: 0,
        assetId: this.data.assetId, //资产id
        channel: 0
      }).then(data => {
        this.setData({
          selectShopId: "",
          showModal: false,
        }, function () {
          wx.showToast({
            title: `优惠券领取成功！`,
            icon: 'none',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                })
              }, 2000)
            }
          })
        })
      }).catch(err => {
        this.setData({
          selectShopId: "",
          showModal: false,
          disabled: false,
        })
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  /**
   *是否显示弹出层
   */
  setShowModel: function (event) {
    if (this.data.assetId) {
      var shopId = event.currentTarget.dataset.id; //页面类型
      this.setData({
        selectShopId: shopId,
        showModal: true
      })
    }
  },
  /**
   *隐藏弹出层
   */
  setHideModel: function (event) {
    this.setData({
      selectShopId: "",
      showModal: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLocation()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})